package com.qnkj.consumer.web;

import com.netflix.hystrix.contrib.javanica.annotation.DefaultProperties;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixCommand;
import com.netflix.hystrix.contrib.javanica.annotation.HystrixProperty;
import com.qnkj.consumer.client.UserClient;
import com.qnkj.consumer.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.cloud.netflix.ribbon.RibbonLoadBalancerClient;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

import java.util.List;


/**
 * @author: zds
 * Date: 2020/5/12  21:22
 * Version: V 1.0
 * Description:
 */
@RestController
@RequestMapping("consumer")
//@DefaultProperties(defaultFallback = "queryByNameFallback")
public class ConsumerController {
    //@Autowired
    //private RestTemplate restTemplate;

    @Autowired
    private UserClient userClient;
    //@Autowired
    //private DiscoveryClient discoveryClient;
    //@Autowired
    //private RibbonLoadBalancerClient client;

    /**
     * 根据用户id查询用
     *
     * @param id
     * @return
     */
    @GetMapping("{id}")
   // @HystrixCommand
    public String queryById(@PathVariable("id") Long id) {

        //方式一
        //根据服务ID获取服务
        //List<ServiceInstance> instances = discoveryClient.getInstances("user-service");
        //随机、轮循、hash
        // ServiceInstance instance = instances.get(0);

        //方式二
      /*  ServiceInstance instance = client.choose("user-service");
        String ip = instance.getHost()+":"+instance.getPort();
        String url = "http://"+ip+"/user/"+id;*/

       // String url = "http://user-service/user/" + id;
        //String user = restTemplate.getForObject(url, String.class);
        //return user;

        return userClient.queryById(id);
    }


    @GetMapping("name/{name}")
    //@HystrixCommand(fallbackMethod = "queryByNameFallback")
   // @HystrixCommand(commandProperties = {@HystrixProperty(name = "execution.isolation.thread.timeoutInMilliseconds",value = "5000")})
   // @HystrixCommand
    public String queryByName(@PathVariable("name") String name) {
        //String url = "http://user-service/user/" + name;
        //String user = restTemplate.getForObject(url, String.class);

        return userClient.queryByName(name);
    }

    public String queryByNameFallback(String name) {
        return "服务器拥挤";
    }

    public String queryByNameFallback() {
        return "服务器拥挤";
    }
}
